<?php

namespace aszx0413\yii2gii;

use yii\helpers\Inflector;

class Field
{
	/**
	 * @var Table
	 */
	public $table;

	/**
	 * @var string 字段名
	 */
	public $name = '';

	/**
	 * @var string 字段中文名
	 */
	public $nameCn  = '';
	public $type    = '';
	public $length  = '';
	public $notNull = ' NOT NULL';
	public $comment = '';
	public $key     = '';

	/**
	 * @var array 配置
	 */
	public $cfg = [];

	public $default = '';

	/**
	 * @var string 枚举
	 */
	public $enum = '';

	/**
	 * @var string 列表属性
	 */
	public $list = '';

	/**
	 * @var string 表单属性
	 */
	public $form = '';

	/**
	 * @var string 该字段关联的表
	 */
	public $hasOne = '';

	/**
	 * @var Table 该字段关联的表
	 */
	public $hasOneTable = null;

	/**
	 * @var string 该字段关联的表
	 */
	public $hasMany = [];

	/**
	 * @param Table[] $tables
	 * @return Table
	 */
	public function getHasToTable($tables)
	{
		if ($this->hasOne != '') {
			$this->hasOneTable = $tables[$this->hasOne];

			return $tables[$this->hasOne];
		}

		return null;
	}

	public function asProperty()
	{
		$name = str_replace('_id', '', $this->name);

		return lcfirst(Inflector::camelize($name));
	}

	public function asLabel()
	{
		if (str_starts_with($this->name, 'parent_')) {
			return '上级';
		} elseif (str_starts_with($this->nameCn, '@')) {
			return $this->hasOneTable->nameCn;
		}

		return $this->nameCn;
	}

	public function isHasMany()
	{
		$many = new Many($this->name);

		if (str_ends_with($this->nameCn, '@')) {
			$many->belongTableName = str_replace('@', '', $this->nameCn);
			$many->relateTable     = $this->table;

			return $many;
		}

		return false;
	}

	public function isList()
	{
		if ($this->type == 'TEXT') {
			return false;
		} elseif (str_contains($this->form, 'P')) {
			return false;
		} elseif (str_contains($this->list, '0')) {
			return false;
		}

		return true;
	}

	public function isSearch()
	{
		if (str_contains($this->list, 'S')) {
			return true;
		}

		return false;
	}

	public function isImg()
	{
		if (str_starts_with($this->name, 'img_')) {
			return true;
		}

		return false;
	}

	public static function parseCfg($str): array
	{
		$cfg = [
			'addDisabled'  => 'false',
			'editDisabled' => 'false',
		];

		$str = explode('|', $str);

		if (in_array('AD', $str)) {
			$cfg['addDisabled'] = 'true';
		}

		if (in_array('E', $str)) {
			$cfg['enum'] = 1;
		}

		if (in_array('ED', $str)) {
			$cfg['editDisabled'] = 'true';
		}

		if (in_array('H', $str)) {
			$cfg['hide'] = 'true';
		} else {
			$cfg['hide'] = 'false';
		}

		if (in_array('R', $str)) {
			$cfg['required'] = 'true';
		} else {
			$cfg['required'] = 'false';
		}

		if (in_array('S', $str)) {
			$cfg['search'] = 'true';
		} else {
			$cfg['search'] = 'false';
		}

		return $cfg;
	}
}
